// kickstart2018roundCproblem3
// Pm:A_j*(N-j+1)*(1^m+2^m+...+j^m), m从1-k
// A_j*(N-j+1)*((1+1^2+...+1^k)+...+(j+j^2+...+j^k))
// 等比数列求和，但j^k太大
// "Since POWER could be huge, print it modulo 1000000007"
// 快速幂:
// X^n = 1, n = 0
// X^n = X^(n/2)*X^(n/2), n&1=0
// X^n = X^(n/2)*X^(n/2)*X, n&1=1
// 取模 (ab)%c = (a%c)(b%c)%c
// 费马小定理 a^(p-1)和1同余
// https://zh.wikipedia.org/wiki/%E8%B4%B9%E9%A9%AC%E5%B0%8F%E5%AE%9A%E7%90%86
// (b/a)%p = (b*a^(p-a))%p

// O(N^2)log(k) 10^12，一般1s是10^9,90s不够：
//  A_j和A_(j+1)系数有重合
// O(N*logk), long long 避免溢出
#include<bits/stdc++.h>
#define MAX_N 1000000
using namespace std;
const long long MOD = 1000000007;

long long fast_pow(long long x, long long n)
{
    if (n == 0) return 1;
    long long ans = fast_pow(x, n / 2);
    if (n % 2 == 0) return ans * ans % MOD;
    return ((ans * ans) % MOD * x % MOD) % MOD;
}
int main()
{
    long long A[MAX_N + 2];
    int T;
    cin >> T;
    for (int ti = 1; ti <= T; ++ti)
    {
        long long N, K, x1, y1, C, D, E1, E2, F;
        cin >> N >> K >> x1 >> y1 >> C >> D >> E1 >> E2 >> F;
        A[1] = (x1 + y1) % F;
        long long xi_last = x1;
        long long yi_last = y1;
        for (int i = 2; i <= N; ++i)
        {
            long long xi, yi;
            xi = (C * xi_last + D * yi_last + E1) % F;
            yi = (D * xi_last + C * yi_last + E2) % F;
            xi_last = xi;
            yi_last = yi;
            A[i] = (xi + yi) % F;
        }
        long long result = 0;
        long long last_sum = 0;
        for (int i = 1; i <= N; ++i)
        {
            if (i == 1) last_sum += K;
            else
            {
                last_sum += i * (fast_pow(i, K) - 1) % MOD 
                    * fast_pow(i - 1, MOD - 2) % MOD;
            }
            last_sum %= MOD;
            long long tmp = last_sum * (N - i + 1) % MOD;
            result += (tmp * A[i] % MOD);
            result %= MOD;
        }
        cout << "Case #" << ti << ": " << result << endl;
    }
    return 0;
}